package com.salary.utils.reader;

import com.salary.model.SalesInfo;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 读工资资料表
 */
public class SalesInfoReader extends DataReader<SalesInfo>{
    private static final Logger logger = LoggerFactory.getLogger(SalesInfoReader.class);

    /**
     * 从Excel文件读取工资资料数据
     *
     * @param filePath Excel文件路径
     * @return 工资资料对象，如果验证失败则返回null
     */
    @Override
    public SalesInfo readData(String filePath) {

        SalesInfo salesInfo = null;

        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = WorkbookFactory.create(fis)) {

            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                logger.error("未找到工作表");
                return null;
            }

            // 查找表头中的列索引
            Row headerRow = sheet.getRow(0);
            if (headerRow == null) {
                logger.error("工资资料表缺少表头行");
                return null;
            }

            // 列索引映射
            Map<String, Integer> columnIndexMap = new HashMap<>();

            // 记录所有表头
            StringBuilder headers = new StringBuilder("工资资料表的列标题：");

            for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                Cell cell = headerRow.getCell(i);
                if (cell == null) continue;

                String cellValue = getCellValueAsString(cell).trim();
                headers.append("[").append(cellValue).append("] ");
                columnIndexMap.put(cellValue, i);
            }

            logger.info(headers.toString());

            // 检查是否包含必要的"姓名"列
            if (!columnIndexMap.containsKey("姓名")) {
                logger.error("工资资料表中未找到姓名列");
                return null;
            }

            // 创建SalaryInfo对象
            salesInfo = new SalesInfo();

            // 从第二行开始读取数据（跳过表头）
            double totalAcceptanceTonnage = 0.0;

            for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (row == null) continue;

                // 获取姓名列的数据
                int nameColIndex = columnIndexMap.get("姓名");
                Cell nameCell = row.getCell(nameColIndex);
                if (nameCell == null) continue;

                String name = getCellValueAsString(nameCell).trim();
                if (name.isEmpty()) continue;

                // 读取所有相关数据

                // 收承兑吨数
                double acceptanceTonnage = 0;
                if (columnIndexMap.containsKey("收承兑吨数")) {
                    Cell cell = row.getCell(columnIndexMap.get("收承兑吨数"));
                    if (cell != null) {
                        acceptanceTonnage = getCellValueAsDouble(cell);
                        if (acceptanceTonnage > 0) {
                            logger.info("读取到业务员收承兑数据: [" + name + "] - " + acceptanceTonnage + "吨");
                            salesInfo.addSalespersonAcceptance(name, acceptanceTonnage);
                            totalAcceptanceTonnage += acceptanceTonnage;
                        }
                    }
                }

                // 超期回款扣款
                if (columnIndexMap.containsKey("超期回款扣款")) {
                    Cell cell = row.getCell(columnIndexMap.get("超期回款扣款"));
                    if (cell != null) {
                        double amount = getCellValueAsDouble(cell);
                        if (amount != 0) {
                            logger.info("读取到业务员超期回款扣款: [" + name + "] - " + amount);
                            salesInfo.setOverduePaymentDeduction(name, amount);
                        }
                    }
                }

                // 超时账单扣款
                if (columnIndexMap.containsKey("超时账单扣款")) {
                    Cell cell = row.getCell(columnIndexMap.get("超时账单扣款"));
                    if (cell != null) {
                        double amount = getCellValueAsDouble(cell);
                        if (amount != 0) {
                            logger.info("读取到业务员未按时交回对账单扣款: [" + name + "] - " + amount);
                            salesInfo.setAccountStatementDeduction(name, amount);
                        }
                    }
                }

                // 营销奖励
                if (columnIndexMap.containsKey("营销奖励")) {
                    Cell cell = row.getCell(columnIndexMap.get("营销奖励"));
                    if (cell != null) {
                        double amount = getCellValueAsDouble(cell);
                        if (amount != 0) {
                            logger.info("读取到业务员营销奖励: [" + name + "] - " + amount);
                            salesInfo.setMarketingReward(name, amount);
                        }
                    }
                }

                // 营销罚款
                if (columnIndexMap.containsKey("营销罚款")) {
                    Cell cell = row.getCell(columnIndexMap.get("营销罚款"));
                    if (cell != null) {
                        double amount = getCellValueAsDouble(cell);
                        if (amount != 0) {
                            logger.info("读取到业务员营销惩罚: [" + name + "] - " + amount);
                            salesInfo.setMarketingPenalty(name, amount);
                        }
                    }
                }

                // 申请补回罚款
                if (columnIndexMap.containsKey("申请补回罚款")) {
                    Cell cell = row.getCell(columnIndexMap.get("申请补回罚款"));
                    if (cell != null) {
                        double amount = getCellValueAsDouble(cell);
                        if (amount != 0) {
                            logger.info("读取到业务员申请补回罚款: [" + name + "] - " + amount);
                            salesInfo.setRefundableDeduction(name, amount);
                        }
                    }
                }
            }

            // 设置总吨数
            salesInfo.setAcceptanceCollection(totalAcceptanceTonnage);

            logger.info("工资资料表读取完成，总收承兑吨数: " + totalAcceptanceTonnage);
            logger.info("业务员收承兑数据: " + salesInfo.getSalespersonAcceptance());

        } catch (IOException e) {
            logger.error("读取Excel文件失败: " + e.getMessage(), e);
        }

        return salesInfo;
    }
}
